<?php

// +-------------------------------------------------------------
// | Name： 星空框架 用户管理模型
// +-------------------------------------------------------------
// | Version: V5.0
// +-------------------------------------------------------------
// | Author: xkyinzhe <zhonghuaxinxing@sina.cn>
// +-------------------------------------------------------------
// | Time: 2021-05-07 11:13
// +-------------------------------------------------------------
declare(strict_types=1);

namespace app\common\model;

use think\facade\Cache;
// use think\Loader;
use think\model\concern\SoftDelete;

//加载phpqrcode
// Loader::import('phpQrcode.phpqrcode',EXTEND_PATH,'.php');
/**
 * @xk 用户管理模型
 */
class User extends BaseModel
{
    use SoftDelete;
    protected $name = 'user';
    protected $pk = 'user_id';
    protected $deleteTime = 'delete_time';
    /**
     * @xk 写入前操作
     *
     * @method onBeforeWrite
     * @param  [type]                  $data                     [description]
     * @return [type]                                            [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-05-07T11:14:40+080
     */
    public static function onBeforeWrite($data)
    {
        unset($data['act']);
        unset($data['controllers']);
        unset($data['actions']);
        if (!$data->create_time) {
            $data->update_time = $data->create_time = date('Y-m-d H:i:s');
        }
        $pass = isset($data['pass']) ? $data['pass'] : '';
        $next_pass = isset($data['next_pass']) ? $data['next_pass'] : '';
        unset($data['next_pass']);
        if ($pass != '' && $pass == $next_pass) {
            $data->pass_key = self::getCodeNo('zxr', 8, 5);
            $data->pass = makePass($pass, $data->pass_key);
        }
    }
    public static function getUserCodeNo()
    {
        //  获取会员编号
        // $start = 1012333;
        // $count = self::count();
        // if ($count <= 0) {
        //     return $start;
        // } else {
        //   // return self::getCodeNo('1092',8,1,'user_sn');
        //   // return self::getCodeNo(date('y').date('W'),8,1,'user_sn');
        //     return self::max('user_sn')+1;
        // }
        // 2023-09-04 会员号改为随机数字组合，同时使用程序进行数据库去重处理
        return self::getCodeNo('',8,1,'user_sn');
    }
    /**
     * @xk 检测手机号
     *
     * @method checkMobile
     * @param  [type]                  $tel                      [description]
     * @param  [type]                  $act                      [description]
     * @return [type]                                            [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-05-07T13:46:20+080
     */
    public static function checkMobile($tel, $act, $user_sn='')
    {
        $condition = [];
        $condition[] = ['tel', '=', $tel];
        switch ($act) {
          case 'register':
            $count = self::where($condition)->count();
            if ($count > 0) {
                return false;
            }

            return true;
          case 'bind':
              $condition[] = ['is_bind','=',1];
              $count = self::where($condition)->count();
              // 判断手机号 和会员号是否为同一个人
              $user_tel = self::where([['user_sn','=',$user_sn]])->value('tel');
              // 判断 当前手机号是否已经绑定过会员 同时会员存在的手机号和会员手机号不一致的情况下返回改手机号已经绑定过了
              if ($count > 0 && $user_tel != $tel) {
                  throw new \think\Exception("当前手机号已经被其他账号绑定，可通过手机号直接登录", 404);
              }
            return true;
            break;
          case 'chanagetel':
            $count = self::where($condition)->count();
            // 判断手机号 和会员号是否为同一个人
            $user_tel = self::where([['user_sn','=',$user_sn]])->value('tel');
            // 判断 当前手机号是否已经绑定过会员 同时会员存在的手机号和会员手机号不一致的情况下返回改手机号已经绑定过了
            if ($count > 0 && $user_tel != $tel) {
                throw new \think\Exception("当前手机号已经被其他账号绑定，可通过手机号直接登录", 404);
            }
            return true;
            break;
            case 'login':
              $count = self::where($condition)->count();
              if ($count <= 0) {
                  return false;
              }
              return true;
              break;
          case 'forget':
            // 判断手机号 和会员号是否为同一个人
            $user_tel = self::where([['user_sn','=',$user_sn]])->value('tel');
            if ($user_tel != $tel) {
                throw new \think\Exception("当前会员号和手机号不匹配，请仔细核对", 404);
            }
            $count = self::where($condition)->count();
            if ($count <= 0) {
                throw new \think\Exception("当前手机号系统不存在，请先使用微信授权注册", 404);
            }
            $tel_status = self::where($condition)->value('status');
            if($tel_status != 1){
              throw new \think\Exception("账号已注销，无法进行密码重置", 404);
            }
            return true;
            break;
        }
        return false;
    }
    /**
     * @xk 检测验证码
     *
     * @method checkCaptch
     * @param  [type]                  $tel                      [description]
     * @param  [type]                  $act                      [description]
     * @param  [type]                  $captch                   [description]
     * @return [type]                                            [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-05-07T13:47:52+080
     */
    public static function checkCaptch($tel, $act, $hasCaptch)
    {
        $captch = $tel ? Cache::get('sms_'.$act.'_'.$tel, '') : '';
        if (!$captch) {
            return false;
        }
        if ($captch != $hasCaptch) {
            return false;
        }
        Cache::delete('sms_'.$act.'_'.$tel);

        return true;
    }
    /**
     * @xk 生成会员二维码
     *
     * @method getUserEwm
     * @param  [type]     $user_sn                   [description]
     * @return [type]     [description]
     * @Time   2021-10-20
     * @City   青岛
     * @Author xkyinzhe   <zhonghuaxinxing@sina.cn>
     */
    public static function getUserEwm($user_sn='', $poster_info=[])
    {
        if (!$user_sn) {
            return  '';
        }
        require_once(__DIR__ . '/../../../extend/phpQrcode/phpqrcode.php');
        $path = 'upload/ewm'; // 用户生成的会员码 每个用户一个
        $share_url = 'https://'.$_SERVER['HTTP_HOST'].'/#/pages/index/index?share_code='.base64_encode($user_sn);
        $qrcode = new \QRcode();
        $value = $share_url;                    //二维码内容
      $errorCorrectionLevel = 'H';    //容错级别
      $matrixPointSize = 2;           //生成图片大小
      ob_start();
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
        }
        $qrcodename = $path.'/'.md5($user_sn.$poster_info).'.png';
        $qrcode::png($value, $qrcodename, $errorCorrectionLevel, $matrixPointSize, 2);
        imagecreatefromstring(file_get_contents($qrcodename));
        return $qrcodename;
    }
    /**
     * @xk 获取上级列表
     * @method          getParentList
     * @param           string $user_sn  [description]
     * @param           array $user_list  [description]
     * @return          [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe <zhonghuaxinxing@sina.cn>
     * @City：           青岛
     * @Time：2022-04-18
     */
    public static function getParentList($user_sn='', $user_list = [],$i=0)
    {
        $user_info = self::alias('u')
               ->leftJoin('userLevel ul', 'u.level = ul.level')
               ->where([['u.user_sn','=',$user_sn]])
               ->field('u.`user_sn`,u.`user_name`,u.`tel`,u.`l_user_sn`,u.`all_achievement_price`,u.`agent_achievement_price`,u.`all_back_money`,u.`purchases_order_price`,u.`create_time`,u.`bind_time`,u.`agent_time`,ul.`level_name`')
               ->find();
        if ($user_info && $user_info['user_sn'] > 0) {
            $user_info = $user_info->toArray();
            $user_info['develop'] = $i;
            $user_list[] = $user_info;
            if ($user_info['l_user_sn'] != '') {
                $i++;
                $user_list = self::getParentList($user_info['l_user_sn'], $user_list,$i);
                return $user_list;
            } else {
                return $user_list;
            }
        }else{
          return $user_list;
        }
    }
    public static function getChildList($user_sn='',$user_list = [],$j=0){
      // 查询第一代会员
      $child_list = self::alias('u')
                    ->leftJoin('userLevel ul', 'u.level = ul.level')
                    ->where([['u.l_user_sn','=',$user_sn]])
                    ->field('u.`user_sn`,u.`user_name`,u.`tel`,u.`l_user_sn`,u.`all_achievement_price`,u.`agent_achievement_price`,u.`all_back_money`,u.`purchases_order_price`,ul.`level_name`')
                    ->select()
                    ->toArray();
      $all_count = count($child_list);
      if($all_count > 0){
        for ($i=0; $i < $all_count; $i++) {
          $user_info = $child_list[$i];
          $user_info['develop'] = $j;
          $user_sn = $user_info['user_sn'];
          $user_list[] = $user_info;
          if($user_info['user_sn'] > 0){
            $user_list = self::getChildList($user_sn,$user_list,$j++);
          }
        }
        return $user_list;
      }else{
        return $user_list;
      }

    }
}
